<?php

namespace App\Models;

use App\Models\Product;
use App\Models\Upload;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ProductsExport implements FromCollection, WithMapping, WithHeadings
{
    public function collection()
    {
       if( isset( $_GET['ids'] ) )
       {
           $ids = $_GET['ids'];
           $ids = trim( $ids, ',');
           $products =  Product::whereIn('id',explode(',',$ids))->get();
           
           
          
           
           
           foreach( $products as $k => &$v )
           {
               
               $uploads = Upload::where('id', $v['thumbnail_img'])->first();
               
               $v->thumbnail_img= $uploads['file_name'];
               $photost = '';
               if( $v['photos'] )
               {
                   $v['photos'] = trim($v['photos']);
                   $photos =  Upload::whereIn('id',explode(',',$v['photos']))->get()->toArray();
                   foreach($photos as $pp )
                   {
                       $photost .= $pp['file_name']."\r\n";
                   }
                   
                    $v->photos= $photost;
               }
               
           }
           
           return $products;
       }
        return Product::all();
    }

    public function headings(): array
    {
        return [
            'name',
           
            'category_id',
            'brand_id',
            'video_provider',
            'video_link',
            'unit_price',
            'purchase_price',
            'unit',
            'current_stock',
            'meta_title',
            'meta_description',
            'thumbnail_img',
            'photos',
            'description',
            'slug',
            'qty',
        ];
    }

    /**
    * @var Product $product
    */
    public function map($product): array
    {
        $qty = 0;
        foreach ($product->stocks as $key => $stock) {
            $qty += $stock->qty;
        }
        return [
            $product->name,
          
            $product->category_id,
            $product->brand_id,
            $product->video_provider,
            $product->video_link,
            $product->unit_price,
            $product->purchase_price,
            $product->unit,
           $product->current_stock,
           $product->meta_title,
           $product->meta_description,
           $product->thumbnail_img,
           $product->photos,
           $product->description,
           $product->slug,
           $qty,
            
        ];
    }
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
}
